package com.smile.aop;

import com.smile.commons.request.RequestIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class LogAspect {

    @Pointcut("execution(public * com.smile.controller.*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint jp) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        try{
            HttpServletRequest request = attributes.getRequest();
            String requestId = null;
            try {
                requestId = RequestIdUtils.get();
            } catch (Exception e) {
                System.out.println("error="+e);
                e.printStackTrace();
                log.error(String.valueOf(e));
                log.error("{}", e.getMessage());
                throw new RuntimeException(e);
            }

            // 记录请求内容
            log.info("request_id={},URL : {}", requestId, request.getRequestURL());
            log.info("request_id={},HTTP 方法 : {}", requestId, request.getMethod());
            log.info("request_id={},IP 地址 : {}", requestId, request.getRemoteAddr());
            log.info("request_id={},类的方法 : {}.{}", requestId, jp.getSignature().getDeclaringTypeName(), jp.getSignature().getName());
            log.info("request_id={},方法参数 : {}", requestId, Arrays.toString(jp.getArgs()));
            System.out.println("=====================doBefore======================");
        }catch (Exception e){
//            e.printStackTrace();
        }

    }


}
